package com.wjw.rabbit.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 简单模式:
 * 消费者(接收消息)
 */
public class Consumer {

    //所有的中间件都是基于TCP/IP协议,RabbitMQ遵循的是amqp协议
    //ip port
    public static void main(String[] args) {
        //1.创建连接工程
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");//RabbitMQ服务的IP
        factory.setPort(5672);//端口
        factory.setUsername("admin");//RabbitMQ的用户
        factory.setPassword("admin");//RabbitMQ的密码
        factory.setVirtualHost("/");//虚拟访问节点

        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接Connection
            connection = factory.newConnection("生产者");
            //3.创建连接获取通道Channel
            channel = connection.createChannel();
            String queueName = "queue1";//队列名称
            /**
             * 4.通过创建交换机、声明队列、绑定关系、路由Key、发生消息或接收消息
             */
            channel.basicConsume("queue2", true, new DeliverCallback() {
                //@Override
                public void handle(String s, Delivery message) throws IOException {
                    System.out.println("从queue1中收到的消息是：" + new String(message.getBody(), "UTF-8"));
                }
            }, new CancelCallback() {
                //@Override
                public void handle(String s) throws IOException {
                    System.out.println("接收消息失败了");
                }
            });

            System.out.println("开始接收消息");
            System.in.read();//阻断,不往下运行
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            //7.关闭通道
            if(channel != null && channel.isOpen()){
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //8.关闭连接
            if(connection != null && connection.isOpen()){
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
